<?php

use phpmailer\phpmailer;
use app\console\model\LoginLog;
use think\Request;
use app\index\model\Integral;
use think\Config;
use Overtrue\EasySms\EasySms;

/**
 * 根据用户的好评数和中评数计算信誉度
 * @param int $praise   好评数
 * @param int $commonly 中评数
 * @param int $negative_comment 差评数
 * @return \think\response\Json
 */
function praise($praise=0, $commonly=0, $negative_comment=0)
{
    $total = $praise + $commonly + $negative_comment;   //总评数
    $praise_total = $total - $negative_comment;   //好评+中评数总数

    if($praise_total == 0){
      return $menber = 0;
    } else{
      return $menber = intval(($praise + $commonly*(4/5))/$total*100);
    }
}

/**
 * 生成toekn
 * @param array $data
 * @param string $msg
 * @return \think\response\Json
 */
function genToken( $len = 50, $md5 = true ) {  
# Seed random number generator  
  # Only needed for PHP versions prior to 4.2  
  mt_srand( (double)microtime()*1000000 );  
  # Array of characters, adjust as desired  
  $chars = array(  
      'Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`',  
      'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.',  
      '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a',  
      'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')',  
      '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n',  
      '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T',  
      'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*'  
  );  
  # Array indice friendly number of chars;  
  $numChars = count($chars) - 1; $token = '';  
  # Create random token at the specified length  
  for ( $i=0; $i<$len; $i++ )  
      $token .= $chars[ mt_rand(0, $numChars) ];  
  # Should token be run through md5?  
  if ( $md5 ) {  
      # Number of 32 char chunks  
      $chunks = ceil( strlen($token) / 32 ); $md5token = '';  
      # Run each chunk through md5  
      for ( $i=1; $i<=$chunks; $i++ )  
          $md5token .= md5( substr($token, $i * 32 - 32, 32) );  
      # Trim the token  
      $token = substr($md5token, 0, $len);  
  } 

  return $token;  
} 


/*
 *  买卖家号码
 */
function order_phone($order_id)
{
    $order_model = new app\index\model\Orders;
    $order_phone = $order_model->alias('o')
        ->where(['order_id'=>$order_id])
        ->join('jk_users b', 'b.user_id = o.buyer_id', 'LEFT')
        ->join('jk_users s', 's.user_id = o.seller_id', 'LEFT')
        ->field('b.username as buyer_phone, s.username as seller_phone')
        ->find();
    return $order_phone;
}

/**
 * 交易短信通知
 *
 * @param $phone int        手机号码
 * @param $template_id string  类型发送短信的模板id
 * @param $order_num string  订单编号
 * @type [
    'SMS_136166526', '您有新的${product}订单，请注意查收！', '发起交易'
    'SMS_136176582', '您发起的订单：${product}，对方已处理，请前往个人中心查看。', '接受或拒绝交易通知'
    'SMS_136166528', '您的订单：${product}，买家已付款请及时发货。', '付款通知（卖家）'
    'SMS_136171647', '您的订单：${product}，已经付款。', '付款通知（买家）'
 ]
 */
function sms_notis($phone, $template_id, $order_num)
{
    $config = [
        'timeout' => 5.0,
        'default' => [
            'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
            'gateways' => [
                'aliyun',
            ],
        ],
        'gateways' => [
            'errorlog' => [
                'file' => '/tmp/easy-sms.log',
            ],
            'aliyun' => [
                'access_key_id' => 'LTAIZiMTSzwt32LT',
                'access_key_secret' => 'YFOSihCfxxnCWWNDxMWIPu2hE4zO9j',
                'sign_name' => '聚咖',
            ],
        ],
    ];
    $easySms = new EasySms($config);
    $aa = $easySms->send(
        $phone,
        [
        'template' => $template_id,
        'data' => [
            'content' => $order_num,
        ],
    ]);

    if($aa){
        return true;
    } else{
        return false;
    }
}

/**
 * 友好的时间显示
 *
 * @param int    $sTime 待显示的时间
 * @param string $type  类型. normal | mohu | full | ymd | other
 * @param string $alt   已失效
 * @return string
 */
function friendlyDate($sTime,$type = 'normal',$alt = 'false') {
    if (!$sTime)
        return '';
    //sTime=源时间，cTime=当前时间，dTime=时间差
    $cTime      =   time();
    $dTime      =   $cTime - $sTime;
    $dDay       =   intval(date("z",$cTime)) - intval(date("z",$sTime));
    //$dDay     =   intval($dTime/3600/24);
    $dYear      =   intval(date("Y",$cTime)) - intval(date("Y",$sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if($type=='normal'){
        if( $dTime < 60 ){
            if($dTime < 10){
                return '刚刚';    //by yangjs
            }else{
                return intval(floor($dTime / 10) * 10)."秒前";
            }
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        //今天的数据.年份相同.日期相同.
        }elseif( $dYear==0 && $dDay == 0  ){
            //return intval($dTime/3600)."小时前";
            return '今天'.date('H:i',$sTime);
        }elseif($dYear==0){
            return date("m月d日 H:i",$sTime);
        }else{
            return date("Y-m-d H:i",$sTime);
        }
    }elseif($type=='mohu'){
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif( $dDay > 0 && $dDay<=7 ){
            return intval($dDay)."天前";
        }elseif( $dDay > 7 &&  $dDay <= 30 ){
            return intval($dDay/7) . '周前';
        }elseif( $dDay > 30 ){
            return intval($dDay/30) . '个月前';
        }
    //full: Y-m-d , H:i:s
    }elseif($type=='full'){
        return date("Y-m-d , H:i:s",$sTime);
    }elseif($type=='ymd'){
        return date("Y-m-d",$sTime);
    }else{
        if( $dTime < 60 ){
            return $dTime."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif($dYear==0){
            return date("Y-m-d H:i:s",$sTime);
        }else{
            return date("Y-m-d H:i:s",$sTime);
        }
    }
}

/**
* 设置邮件格式
* $title 标题
* $user_email 收件人邮箱
* $code 生成的验证码
* $username 用户名
*/
function setEmail($title, $user_email, $code, $username)
{
    $time = date('Y-m-d', time());
    $content = "<!DOCTYPE html>
                <html>
                <head>
                <meta charset='utf-8'>
                </head>
                <body>
                <style>
                *{ padding: 0; margin: 0}a{ text-decoration: none;color: #428bca;}div{width: 500px; padding:10px; margin: 0 auto; border-top: 5px solid #428bca;margin-top: 20px;box-shadow: 0px 0px 5px #ccc;}h2{ text-align: left; padding: 10px;}p{ font-size: 14px; color: #808080; text-align: left;}</style>
                <div><h2>聚咖网络<h2><p>尊敬的".$username.",您正在绑定邮箱, 验证码是: <b style='color:#428bca'>".$code."</b><p><br/><p>有效期两小时<p><p>".$time."<p></div>
                </body>
                </html>";
    $data = array(
        array(
            'title' => $title,
            'user_email' => $user_email,
            'content' => $content
        ),
    );

    return $data;

}

/**
* 发送邮箱
* @param type $data 邮箱队列数据 包含邮箱地址 内容
* $data = array(
*  'title' =>'标题'
*  'user_email' =>'邮箱'
*  'content' =>'内容'
*)
*/
function sendEmail($data = []) {
  Vendor('phpmailer.phpmailer');
  $mail = new PHPMailer(); //实例化
  $mail->IsSMTP(); // 启用SMTP
  $mail->Host = Config::get('SMTP_SERVER'); //SMTP服务器 以126邮箱为例子
  $mail->Port = Config::get('SMTP_PORT');  //邮件发送端口
  $mail->SMTPAuth = true;  //启用SMTP认证
  $mail->SMTPSecure = Config::get('EMAIL_SMTP_SECURE');   // 设置安全验证方式为ssl
  $mail->CharSet = "UTF-8"; //字符集
  $mail->Encoding = "base64"; //编码方式
  $mail->Username = Config::get('SMTP_USER');  //你的邮箱
  $mail->Password = Config::get('SMTP_PWD');  //你的密码
  $mail->Subject = $data[0]['title']; //邮件标题
  $mail->From = Config::get('SMTP_USER');  //发件人地址（也就是你的邮箱）
  $mail->FromName = Config::get('EMAIL_FROM_NAME');  //发件人姓名
  if($data && is_array($data)){
    foreach ($data as $k=>$v){
      $mail->AddAddress($v['user_email'], "亲"); //添加收件人（地址，昵称）
      $mail->IsHTML(true); //支持html格式内容
      $mail->Body = $v['content']; //邮件主体内容
      //发送成功就删除
      if ($mail->Send()) {
        // echo "发送成功";
        return true;
      }else{
          echo "Mailer Error: ".$mail->ErrorInfo;// 输出错误信息
      }
    }
  }
}


/*
 *  积分入库管理
 *  $channel 来源渠道|1：登录， 2:注册, 3：发布文章，4：交易成功赠送 5:邀请注册 6：消费积分
 *  $type 类型|1：增加，2：减少
 *  $menber 数量
 */
function add_signin($channel, $type, $menber, $user_id, $content)
{
    $res = Integral::create([
        'user_id' => $user_id,
        'channel' => $channel,
        'type' => $type,
        'menber' => $menber,
        'content' => $content,
        'create_at' => time(),
    ]);

    return $res;
}

/*
 *  价格
 *  1,买家支付 2,卖家支付 3,双方均摊 4,双向收费（新媒体）
 *
 *  buyer_price 买家需付金额
 *  seller_price 卖家实收金额
 *  profit 平台利润
 */
function price_detail($order_id){
    //设置收费比例
    $proportion = Config::get('web.reat_of_charge')/100;

    $orders = new \app\index\model\Orders;
    $order_info = $orders->where('order_id', $order_id)->find();

    //收费类型
    $agency_fee_type = $order_info->agency_fee_type;
    //交易金额
    $price = $order_info->price;

    if($agency_fee_type == 1){
        $data['buyer_price'] = $price * (1 + $proportion);
        $data['seller_price'] = $price;
        $data['profit'] = $price * $proportion;
    }elseif ($agency_fee_type == 2){
        $data['buyer_price'] = $price;
        $data['seller_price'] = $price * (1 - $proportion);
        $data['profit'] = $price * $proportion;
    }elseif($agency_fee_type == 3){
        $data['buyer_price'] = $price * (1 + $proportion/2);
        $data['seller_price'] = $price * (1 - $proportion/2);
        $data['profit'] = $price * $proportion;
    }elseif($agency_fee_type == 4){
        $data['buyer_price'] = $price * (1 + $proportion);
        $data['seller_price'] = $price * (1 - $proportion);
        $data['profit'] = $price * ($proportion * 2);
    }else{
        return false;
    }

    return $data;
}

/*
 *  预算价格
 *  price 交易金额
 *  1,买家支付 2,卖家支付 3,双方均摊 4,双向收费（新媒体）
 *
 *  buyer_price 买家需付金额
 *  seller_price 卖家实收金额
 */
function price_budget($price,$type){
    //设置收费比例
    $proportion = Config::get('web.reat_of_charge')/100;

    if($type == 1){
        $data['buyer_price'] = $price * (1 + $proportion);
        $data['seller_price'] = $price;
    }elseif ($type == 2){
        $data['buyer_price'] = $price;
        $data['seller_price'] = $price * (1 - $proportion);
    }elseif($type == 3){
        $data['buyer_price'] = $price * (1 + $proportion/2);
        $data['seller_price'] = $price * (1 - $proportion/2);
    }elseif($type == 4){
        $data['buyer_price'] = $price * (1 + $proportion);
        $data['seller_price'] = $price * (1 - $proportion);
    }else{
        return false;
    }

    return $data;
}

/*
* 管理员登录日志
*  @content  内容
*  @type  1:登录日志 2：操作日志
*/
function set_log($type, $content)
{
    $request = Request::instance();
    LoginLog::create([
        'user_id' => session('adminInfo')['id'],
        'ip' => $request->ip(),
        'create_at' => time(),
        'type' => $type,
        'content' => $content
    ]);

    return true;
}

/**
 * 生成唯一的订单编号
 * @return string
 */
function get_order_num()
{
    @date_default_timezone_set("PRC");
    $order_date = date('Y-m-d');
    $order_id_main = date('YmdHis') . rand(10, 99); 
    $order_id_len = strlen($order_id_main);      
    $order_id_sum = 0;
    for ($i = 0; $i < $order_id_len; $i++) {
        $order_id_sum += (int)(substr($order_id_main, $i, 1));
    }
    $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);    
    return $order_id;
}

/**
 * 接口返回成功
 * @param array $data
 * @param string $msg
 * @return \think\response\Json
 */
function success($data = [], $msg = '')
{
    $response = array(
        'code' => 0,
        'message' => $msg,
        'data' => $data,
    );
    return json($response, 200, ['Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Headers' => 'x-requested-with,content-type',
        'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,DELETE']);
}

/**
 * 分页格式化
 * @param string $name 数据名
 * @param array|\think\Paginator $pageData
 * @return array
 */
function formatPage($name, $pageData)
{
    if (!is_array($pageData)) {
        $pageData = $pageData->toArray();
    }
    $pages = $pageData['last_page'];
    $data = $pageData['data'];
    return [$name => $data, 'pages' => $pages];
}

/**
 * 接口返回失败
 * @param string $msg
 * @param array $data
 * @return \think\response\Json
 */
function error($msg = '', $data = [])
{
    $response = array(
        'code' => 1,
        'message' => $msg,
        'data' => $data,
    );
    return json($response, 200, ['Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Headers' => 'x-requested-with,content-type',
        'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,DELETE']);
}

/*
 *  这个函数名一定要怪
 *
 *  删除目标文件夹及其所有子目录
 *  $path 文件夹路径
 * @return 无返回。请查看目标文件或文件夹是否存在判断是否执行成功
 */
function recursively_careful($path)
{
    if(is_dir($path))
    {
        $file_list= scandir($path);
        foreach ($file_list as $file)
        {
            if( $file!='.' && $file!='..')
            {
                recursively_careful($path.'/'.$file);
            }
        }
        @rmdir($path);
        //这种方法不用判断文件夹是否为空,
        //因为不管开始时文件夹是否为空,到达这里的时候,都是空的
    }
    else
    {
        @unlink($path);
        //这两个地方最好还是要用@屏蔽一下warning错误,看着闹心
    }
}